package com.gxuwz.stats.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.stats.entity.AcademicWork;
import com.gxuwz.stats.entity.DecisionConsulting;
import com.gxuwz.stats.entity.User;
import com.gxuwz.stats.security.jwt.JwtTokenUtil;
import com.gxuwz.stats.service.DecisionConsultingService;
import com.gxuwz.stats.service.UserService;
import com.gxuwz.stats.utils.ExcelExportUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/decisionConsulting")
public class DecisionConsultingController {

    @Autowired
    private DecisionConsultingService decisionConsultingService;

    @Autowired
    private UserService userService;

    /**
     * 分页查询决策咨询数据
     */
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getConsultingList(
            @RequestParam Map<String, String> params,
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize) {
        try {

            IPage<DecisionConsulting> page = new Page<>(currentPage, pageSize);
            QueryWrapper<DecisionConsulting> queryWrapper = new QueryWrapper<>();

            // 根据用户名获取用户ID列表并加入查询条件
            if (params.containsKey("username") && !params.get("username").trim().isEmpty()) {
                List<String> userIds = userService.getUserIdsByKeyword(params.get("username"));
                if (!userIds.isEmpty()) {
                    queryWrapper.in("user_id", userIds);
                } else {
                    // 如果没有找到对应的userId，则返回空结果
                    queryWrapper.eq("1", "0");
                }
            }

            // 模糊查询条件 - 项目名称
            if (params.containsKey("consultingResultName") && params.get("consultingResultName") != null && !params.get("consultingResultName").isEmpty()) {
                queryWrapper.like("consulting_result_name", params.get("consultingResultName"));
            }

            // 模糊查询条件 - 项目级别
            if (params.containsKey("consultingCategory") && params.get("consultingCategory") != null && !params.get("consultingCategory").isEmpty()) {
                queryWrapper.like("consulting_category", params.get("consultingCategory"));
            }

            // 模糊查询条件 - 获得时间
            if (params.containsKey("consultingYear") && params.get("consultingYear") != null && !params.get("consultingYear").isEmpty()) {
                queryWrapper.apply("YEAR(consulting_year) = {0}", params.get("consultingYear"));
            }

            // 模糊查询条件 - 审核状态
            if (params.containsKey("consultingReviewStatus") && params.get("consultingReviewStatus")!= null &&!params.get("consultingReviewStatus").isEmpty()) {
                queryWrapper.eq("consulting_review_status", params.get("consultingReviewStatus"));
            }

            // 查询条件 - 提交状态
            if (params.containsKey("consultingStatus") && params.get("consultingStatus") != null && !params.get("consultingStatus").isEmpty()) {
                queryWrapper.eq("consulting_status", params.get("consultingStatus"));
            }

            IPage<DecisionConsulting> resultPage = decisionConsultingService.getDecisionConsultingList(page, queryWrapper);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "查询成功");
            response.put("data", resultPage.getRecords());
            response.put("total", resultPage.getTotal());
            response.put("currentPage", resultPage.getCurrent());
            response.put("pageSize", resultPage.getSize());
            response.put("totalPages", resultPage.getPages());

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 新增决策咨询数据
     */
    @PostMapping("/add")
    public ResponseEntity<Map<String, Object>> saveConsulting(@RequestBody DecisionConsulting decisionConsulting) {
        String username = decisionConsulting.getUsername(); // 从前端获取的用户名
        if (username == null || username.isEmpty()) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("msg", "用户名不能为空");
            return ResponseEntity.badRequest().body(response);
        }
        // 根据用户名获取用户信息
        User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
        if (user == null) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("msg", "用户不存在");
            return ResponseEntity.badRequest().body(response);
        }

        String userId = user.getUserId();

        // 判断该用户是否已经在 total_work 表中存在记录
//        QueryWrapper<DecisionConsulting> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("user_id", userId);
//        int count = decisionConsultingService.count(queryWrapper);
//
//        if (count > 0) {
//            Map<String, Object> response = new HashMap<>();
//            response.put("code", 400);
//            response.put("msg", "该用户已存在，不能重复新增");
//            return ResponseEntity.badRequest().body(response);
//        }

        // 设置 userId 并保存
        decisionConsulting.setUserId(userId);

        int baseScore = decisionConsultingService.getScoreByType(decisionConsulting.getConsultingCategory());
        decisionConsulting.setConsultingScore(baseScore);
        // 2. 计算总分值并保存
//        decisionConsultingService.calculateTotalScore(decisionConsulting);

        decisionConsulting.setConsultingStatus("已提交");
        decisionConsulting.setConsultingReviewStatus("未审核");
        decisionConsulting.setConsultingSubmissionTime(LocalDateTime.now());

        decisionConsultingService.save(decisionConsulting);

        // 4.总分值-提取年份
        String year = null;
        if (decisionConsulting.getConsultingYear() != null) {
            try {
                // 支持 "yyyy-MM" 或 "yyyy/MM" 或 "yyyy" 格式
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                year = sdf.format(decisionConsulting.getConsultingYear());
            } catch (Exception e) {
                // 如果格式不对，兜底取前4位
                year = decisionConsulting.getConsultingYear().substring(0, 4);
            }
        }
        if (year != null) {
            decisionConsultingService.updateTotalWorkDecisionConsultingScore(userId, year);
        }

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "新增成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 批量删除决策咨询数据
     */
    @DeleteMapping("/delete")
    public ResponseEntity<Map<String, Object>> deleteConsulting(@RequestBody List<Long> ids) {
        // 1. 查出所有要删的数据
        List<DecisionConsulting> toDelete = decisionConsultingService.listByIds(ids);

        // 2. 记录所有受影响的 userId+year 组合
        Set<String> userYearSet = new HashSet<>();

        for (DecisionConsulting dc : toDelete) {
            if (dc.getUserId() != null && dc.getConsultingYear() != null) {
                String year = null;
                try {
                    // 支持 "yyyy-MM" 或 "yyyy/MM" 或 "yyyy" 格式
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                    year = sdf.format(dc.getConsultingYear());
                } catch (Exception e) {
                    // 如果格式不对，兜底取前4位
                    year = dc.getConsultingYear().substring(0, 4);
                }
                userYearSet.add(dc.getUserId() + "#" + year);
            }
        }

        // 3. 删除
        decisionConsultingService.removeByIds(ids);

        // 4. 删除后，逐个更新 TotalWork
        for (String userYear : userYearSet) {
            String[] arr = userYear.split("#");
            String userId = arr[0];
            String year = arr[1];
            decisionConsultingService.updateTotalWorkDecisionConsultingScore(userId, year);
        }

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "删除成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 修改决策咨询数据
     */
    @PutMapping("/update")
    public ResponseEntity<Map<String, Object>> updateConsulting(@RequestBody DecisionConsulting decisionConsulting) {
        // 1. 获取前端传递的用户名
        String username = decisionConsulting.getUsername();
//        System.out.println("shdjs="+username);
        if (username != null && !username.isEmpty()) {
            // 2. 查询用户信息
            User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
//            System.out.println("user="+user);
            if (user == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 400);
                response.put("msg", "用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
            // 3. 设置 userId
            decisionConsulting.setUserId(user.getUserId());
        }

        int baseScore = decisionConsultingService.getScoreByType(decisionConsulting.getConsultingCategory());
        decisionConsulting.setConsultingScore(baseScore);
        decisionConsultingService.updateById(decisionConsulting);

        //总分值
        String year = null;
        if (decisionConsulting.getConsultingYear() != null) {
            try {
                // 支持 "yyyy-MM" 或 "yyyy/MM" 或 "yyyy" 格式
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                year = sdf.format(decisionConsulting.getConsultingYear());
            } catch (Exception e) {
                // 如果格式不对，兜底取前4位
                year = decisionConsulting.getConsultingYear().substring(0, 4);
            }
        }
        if (year != null) {
            decisionConsultingService.updateTotalWorkDecisionConsultingScore(decisionConsulting.getUserId(), year);
        }

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "修改成功");
        return ResponseEntity.ok(response);
    }

    @PostMapping("/review")
    public ResponseEntity<Map<String, Object>> reviewDecisionConsulting(@RequestBody Map<String, Object> params) {
        Map<String, Object> response = new HashMap<>();
        try {
            Long consultingId = Long.valueOf(params.get("consultingId").toString());
            String reviewStatus = params.get("reviewStatus").toString(); // 审核通过/审核不通过
            String reviewResult = params.get("reviewResult") != null ? params.get("reviewResult").toString() : "";

            DecisionConsulting consulting = decisionConsultingService.getById(consultingId);
            if (consulting == null) {
                response.put("code", 404);
                response.put("msg", "数据不存在");
                return ResponseEntity.ok(response);
            }

            // 设置审核状态、审核时间、审核说明
            consulting.setConsultingReviewStatus(reviewStatus);
            consulting.setConsultingReviewTime(java.time.LocalDateTime.now());
            consulting.setConsultingReviewResult(reviewResult);

            if ("审核通过".equals(reviewStatus)) {
                consulting.setConsultingReviewResult(null); // 审核通过时清空说明
            }
            if ("审核不通过".equals(reviewStatus)) {
                consulting.setConsultingStatus("未提交");
            }

            decisionConsultingService.updateById(consulting);

            response.put("code", 200);
            response.put("msg", "审核成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("code", 500);
            response.put("msg", "审核失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @GetMapping("/export")
    public void exportDecisionConsulting(
            @RequestParam(value = "year", required = false) String year,
            HttpServletResponse response) throws Exception {

        // 3. 查询 DecisionConsulting（可按年份筛选）
        QueryWrapper<DecisionConsulting> queryWrapper = new QueryWrapper<>();

        if (year != null && !year.isEmpty()) {
            queryWrapper.like("consulting_year", year.substring(0, 4));
        }

        // 只导出审核通过的数据
        queryWrapper.eq("consulting_status", "已提交");

        List<DecisionConsulting> list = decisionConsultingService.list(queryWrapper);

        // 4. 查询所有用户，构建 userId -> username 映射
        List<User> userList = userService.list();
        Map<String, String> userIdNameMap = userList.stream()
                .collect(Collectors.toMap(User::getUserId, User::getUsername, (a, b) -> a));
        for (DecisionConsulting w : list) {
            w.setUsername(userIdNameMap.getOrDefault(w.getUserId(), ""));
        }

        // 5. 给每条数据加序号
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setRowNum(i + 1); // 从1开始
        }

        // 6. 生成文件名
        String now = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
        String fileName = "决策咨询类-" + now + ".xlsx";
//        fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");

        // 7. 导出
        ExcelExportUtil.export(response, list, DecisionConsulting.class, "决策咨询", fileName);
    }
}